#coding:utf-8

import sys

try:
    reload(sys)
    sys.setdefaultencoding("utf-8")
except:
    pass

from window import *
from PyQt4 import QtGui,QtCore

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s


#####
# 目标站点 
#####

DOMAIN  = "http://www.dmzj.com"
IMG_SRV = "http://imgfast.dmzj.com/"  #图片服务器地址
# 
# 
import os
from os.path import exists


TMP_PATH = os.environ['HOME']+"/Library/Pboo/cache"
if not exists(TMP_PATH):
    os.makedirs(TMP_PATH)

USER_HOME = TMP_PATH+"/.."

#print(content2)



#hp = HomePageHTMLParser()
#hp.feed(content2)
#hp.close()
#print(hp.links)
#print(hp.title)

#http://imgfast.dmzj.com/j/%E5%AF%84%E7%94%9F%E5%85%BD/1/_H01-_0137.jpg#

#http://imgfast.dmzj.com/j/%E5%AF%84%E7%94%9F%E5%85%BD/VOL_01/KISEIJU_01_004.jpg


import lib
### 抓去第一次。 
#h2 = httplib2.Http('.cache')
#resp2,content2 = h2.request("http://www.dmzj.com/jss")
#hp = lib.HomePageHTMLParser("寄生")
#hp.feed(content2)
#hp.close()
#print(hp.links)

#print( lib.GetCartoonInfoByWebdriver("http://www.dmzj.com/zhanchangnvshen/567.shtml") )
#h2 = httplib2.Http('.cache')
#resp2,content2 = h2.request("http://www.dmzj.com/zhanchangnvshen/567.shtml")

#info = lib.GetCartoonInfo(content2)
#for x in info["all_page"]:
#    print(x)

import threading
import os
import httplib2
try:
    from Queue import Queue
except ImportError:
    from queue import Queue
    
import json
import time

CLOSE = Queue(0)
download  = httplib2.Http('.cache')

AllBook = []
AllBookWantList = []
SaveBookThread = []


def SaveBooks():
    global SaveBookThread
    bookjson = json.dumps(AllBook)
    f = open(USER_HOME+"/bookhistory.json" , "wb")
    f.write(bookjson)
    f.close()
    SaveBookThread.pop(0)
    
class EmittingStream(QtCore.QObject):

    textWritten = QtCore.pyqtSignal(str)

    def write(self, text):
        self.textWritten.emit(str(text))

class MessageForm(QtGui.QMainWindow , Ui_MainWindow  ):
    _GetHomePageThrend = {}
    BookList = {}
    pages = []
    PageIndex = 0
    AutoDownload  = []
    _downThread = []
    def __init__(self):
        QtCore.QTextCodec.setCodecForTr(QtCore.QTextCodec.codecForName("utf8"))
        
        QtGui.QMainWindow.__init__(self)
        # Ui_MainWindow.__init__(self, MessageForm)
        super(MessageForm,self).__init__(self)
        super(Ui_MainWindow, self).__init__(self)
        self.setupUi(self)
        self.retranslateUi(self)
        self.InitAction()
        self.treeWidget.setHeaderLabels([_fromUtf8("章节") ])
        sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
        if exists(USER_HOME+"/bookhistory.json"):
            f = open(USER_HOME+"/bookhistory.json", "rb")
            bb = f.read()
            f.close()
            global AllBook 
            global AllBookWantList
            print(bb)
            if len(bb)>0:
                AllBook = json.loads(bb)
                AllBookWantList = json.loads(bb)
        #漫画抓去线程
        t = threading.Thread(target= self.BuildBooKAll)
        t.start()

        t = threading.Thread(target=self.AutoLoad , args=[] )
        t.start()
        
    def normalOutputWritten(self, text):
        """Append text to the QTextEdit."""
        # Maybe QTextEdit.append() works as well, but this is how I do it:
        cursor = self.logEdit.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText(text)
        self.logEdit.setTextCursor(cursor)
        self.logEdit.ensureCursorVisible()

    def InitAction(self ):

        self.getBut.clicked[bool].connect(self.actionGetC)
        #self.connect(self.quitRoomBut, QtCore.SIGNAL('clicked()'),QtGui.qApp, QtCore.SLOT('quit()'))
        self.treeWidget.connect(self.treeWidget, QtCore.SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), self.actionBookMenuClick)

        self.NextPageBut.clicked[bool].connect(self.actionNextPage)

        self.PrivPageBut.clicked[bool].connect(self.actionPrivPage)
        self.HomePageBut.clicked[bool].connect(self.actionHomePage)
        self.EndPageBut.clicked[bool].connect(self.actionEndPage)

    def AutoLoad(self):
        while True:
            
            if not CLOSE.empty():
                CLOSE.get(block = False)
                break
                
            if len(self.AutoDownload) > 0 :
                u = self.AutoDownload.pop(0)
                tmp = "%s/%s" % (TMP_PATH , u )
                print (u"Download file:%s\n" % tmp)
                r,c = download.request("%s/%s"  % (IMG_SRV , u ))

                if not os.path.exists(tmp):
                    tmpdir = os.path.split(os.path.realpath(tmp))[0]
                    if not os.path.exists(tmpdir):
                        os.makedirs(tmpdir)
                    f = open(tmp , "wb")
                    f.write(c)
                    f.close()
                continue
            
            time.sleep(5)
            
        print("download stop %d !" % len(self.AutoDownload)) 


    #//所有目录
    def BuildBooKAll(self):
        global AllBookWantList
        def delThread(Book):
            if Book.has_key("name"):
                self.BookList[Book["name"]] = Book
                root = QtGui.QTreeWidgetItem(self.treeWidget)
                root.setText(0,_fromUtf8(Book["name"]))
                i=0
                for Val  in Book["list"]:
                    t = QtGui.QTreeWidgetItem(root)
                    t.ReadPage = 0
                    t.AllPage  = Val["max_page"]
                    t.Number = i
                    t.setText(0, _fromUtf8("%s %d/%d " % (Val["title"]  , t.ReadPage , t.AllPage ) ) )
                    t.Book = Val["name"]
                    if Val.has_key("all_page"):
                        for u in Val["all_page"]:
                            self.AutoDownload.append(u)
                    i+=1

        while True:
            if not CLOSE.empty():
                CLOSE.get(block = False)
                break
            if len(AllBookWantList) >0 :
                url , tag = AllBookWantList.pop(0)
                lib.BuildHomePage(DOMAIN , url , tag , delThread)
            time.sleep(0.1)

    def actionGetC(self):
        global AllBookWantList
        #获取章节数据
        url  = "%s/%s" %  (DOMAIN, self.cUrlEdit.text().toUtf8())
        tag = "%s" % self.cTagEdit.text().toUtf8()

        AllBookWantList.append([url,tag])
        AllBook.append([url,tag])
        t  = threading.Thread(target=SaveBooks)
        SaveBookThread.append(t)
        t.start()
            
        #lib.BuildHomePage(url, tag, delThread )

    def actionBookMenuClick(self,item , cols):
        try:
            self.pages = self.BookList[item.Book]["list"][item.Number]["all_page"]
            self.PageIndex = 0
            self.showImage()
        except AttributeError as e:
            pass
    #下一页
    def actionNextPage(self):
        if self.PageIndex < len(self.pages):
            self.PageIndex +=1
        self.showImage()

    #上一页
    def actionPrivPage(self):
        if self.PageIndex >0 :
            self.PageIndex -= 1
        self.showImage()

    def actionHomePage(self):
        self.PageIndex = 0
        self.showImage()

    def actionEndPage(self):
        self.PageIndex = len(self.pages) -1
        self.showImage()
    def showImage(self):
        if len(self.pages) > self.PageIndex:
            url = "%s/%s" % (TMP_PATH , self.pages[self.PageIndex])
            self.imageBrow.setText( "%s<br/><img src='%s' height=900 >" % (url,url) )


    def closeEvent(self,event):
        CLOSE.put(True)
        CLOSE.put(True)
        event.accept()
        print("Quit ")


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    msgform = MessageForm()
    msgform.show()
    sys.exit(app.exec_())




